package com.leet.code.lcof;

import com.algorithm.model.TreeNode;

import java.util.HashMap;

public class Code07_R {



    public static void main(String[] args) {


    }
    HashMap<Integer, Integer> inorderMap;
    int[] preorder;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        inorderMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            inorderMap.put(inorder[i], i);
        }


        return recur(0, 0, inorder.length - 1);
    }


    public TreeNode recur(int rootIndex, int leftIndex, int rightIndex) {
        if (leftIndex > rightIndex) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[rootIndex]);
        int inorderIndex = inorderMap.get(preorder[rootIndex]);

        root.left = recur(rootIndex + 1, leftIndex, inorderIndex - 1);
        root.right = recur(rootIndex + (inorderIndex - leftIndex) + 1, inorderIndex + 1, rightIndex);
        return root;
    }


}
